import { Router, Request } from 'express'
import { USER, STUDENT, StudentData } from '../../db/model'
import { transaction, update } from '../../db/dao'

interface RequestWithBody extends Request{
  body: {
    type: string;
    data: StudentData;
  };
}

const router = Router()

router.put('/edit', async (req: RequestWithBody, res) => {
  const { type, data } = req.body
  const accountData = {
    identity: type
  }
  transaction(session => Promise.all([
    update(USER, {
      account: data.account
    }, accountData, { session }, true),
    update(STUDENT, {
      account: data.account
    }, data, { session }, true)
  ])).then(data => {
    res.status(200).json({
      message: '修改成功',
      data
    })
  }).catch(() => {
    res.status(500).end()
  })
})

export default router
